package com.pyip.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyip.reggie.Entity.ShoppingCart;
import com.pyip.reggie.Entity.User;
import com.pyip.reggie.common.BaseContext;
import com.pyip.reggie.common.R;
import com.pyip.reggie.mapper.ShoppingCartMapper;
import com.pyip.reggie.mapper.UserMapper;
import com.pyip.reggie.service.ShoppingCartService;
import com.pyip.reggie.service.UserService;
import com.pyip.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public R<ShoppingCart> addShoppingCart(ShoppingCart shoppingCart) {
        // 设置用户id
        Long currentId = BaseContext.getCurrent();
        shoppingCart.setUserId(currentId);

        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId,currentId);

        if(dishId !=null){
            // 添加的是菜品
            sclqw.eq(ShoppingCart::getDishId,dishId);
        }else{
            // 添加的是套餐
           sclqw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        // 查询当前菜品（套餐）是否在购物车中
        ShoppingCart one = this.getOne(sclqw);
        if(one != null){
            // 已经存在了，在此基础上数量+1
            one.setNumber(one.getNumber()+1);
            // 更新数据
            this.updateById(one);
        }else{
            // 不存在，添加数据
            shoppingCart.setNumber(1);
            // 不能添加自动填充（没有其他三个公共填充的，只有这一个）
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            one = shoppingCart;
        }
        return R.success(one);
    }

    @Override
    public R<List<ShoppingCart>> getShoppingCartList() {
        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId,BaseContext.getCurrent());
        sclqw.orderByAsc(ShoppingCart::getCreateTime);
        return R.success(this.list(sclqw));
    }

    @Override
    public R<String> removeShoppingCart() {
        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId,BaseContext.getCurrent());

        return this.remove(sclqw) ? R.success("清空购物车成功") : R.error("清空购物车失败");
    }
}
